<template>
  <div class="reportDetailContainer">
    <div class="wrapper" id="wrapper">
      <!-- 头部 -->
      <van-nav-bar title="扬尘监测" left-arrow @click-left="onClickLeft">
      </van-nav-bar>
      <div class="wetherCont">
        <!-- 值 -->
        <div class="weather f fb">
          <div class="middleCont_left fl">
            <p class="top1">pm2.5</p>
            <p class="top">
              {{
                environmentalData.pm25MeasuredValue != null
                  ? environmentalData.pm25MeasuredValue
                  : "-"
              }}/{{
                environmentalData.pm25WbReleaseValue != null
                  ? environmentalData.pm25WbReleaseValue
                  : "-"
              }}
            </p>
            <p class="bot f fc">实测值/气象站</p>
          </div>
          <div class="middleCont_middle"></div>
          <div class="middleCont_left fl">
            <p class="top1">pm10</p>
            <p class="top">
              {{
                environmentalData.pm10MeasuredValue != null
                  ? environmentalData.pm10MeasuredValue
                  : "-"
              }}/{{
                environmentalData.pm10WbReleaseValue != null
                  ? environmentalData.pm10WbReleaseValue
                  : "-"
              }}
            </p>
            <p class="bot f fc">实测值/气象站</p>
          </div>
          <div class="middleCont_middle"></div>
          <div class="middleCont_left fl">
            <p class="top1">更新时段</p>
            <p class="top">
              {{
                environmentalData.measuredUpdatePeriod != null
                  ? environmentalData.measuredUpdatePeriod
                  : "-"
              }}
            </p>
            <p class="bot f fc">单位：ug/㎥</p>
          </div>
        </div>
      </div>
      <div class="reportCont">
        <!-- 环境评价 -->
        <div class="hjpj">
          <div class="top f fb">
            <div class="left fl">
              <ul class="title_ul f">
                <li
                  class="title_li"
                  v-for="(item, index) in titleList"
                  :key="index"
                  :class="{ title_li_act: titleIndex == index }"
                  @click="titleTap(index, item.id)"
                >
                  {{ item.title }}
                </li>
              </ul>
            </div>
            <div class="right f fc" @click="toHistory">历史数据</div>
          </div>
          <div class="hjpj_cont f fb">
            <div
              class="left f fc"
              v-bind:style="{ color: activeColor, borderColor: activeColor }"
            >
              {{
                environmentalData.qualityLevelContent &&
                environmentalData.qualityLevelContent.slice(0, 2)
              }}
            </div>
            <div class="right fl">
              <progressLite
                :value="progress.value"
                :data="progress"
                id="pro-1"
                :height="80"
              />
            </div>
          </div>
        </div>
        <!-- 施工场界实时监测值 -->
        <div class="cont">
          <div class="contTitle f fb">
            <div class="f">
              <van-icon name="arrow" class="right" />施工场界实时监测值
            </div>

            <div class="btitle">预警0次</div>
          </div>
          <div class="echartDiv" id="data1"></div>
        </div>
        <!-- 功能区影响值 -->
        <div class="cont">
          <div class="contTitle f fb">
            <div class="f">
              <van-icon name="arrow" class="right" />Data2前一小时平均值
            </div>

            <div class="btitle">{{ chart2.subtitle }}</div>
          </div>
          <div class="echartDiv" id="data2"></div>
        </div>
        <!-- 前20分钟等级效声级 -->

        <div class="cont">
          <div class="contTitle f fb">
            <div class="f">
              <van-icon name="arrow" class="right" />Data3前一天监测平均值
            </div>

            <div class="btitle">{{ chart3.subtitle }}</div>
          </div>
          <div class="echartDiv" id="data3"></div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
var projectId = localStorage.getItem("projectid");
import {
  getEnvironmentalData,
  getDustSet,
  selectDustChartByReal,
  selectDustChartByHour,
  selectDustChartByDay,
} from "@/api/api";
import progressLite from "../progressLite.vue";
const text = ["PM2.5", "PM10"];
import moment from "moment";
export default {
  components: {
    progressLite,
  },
  data() {
    return {
      //日历

      titleList: [
        { id: 1, title: "PM2.5" },
        { id: 2, title: "PM10" },
      ],
      titleIndex: 0,
      //PM 面板数据
      environmentalData: {
        qualityLevelContent: "-",
      },
      pm25StandardLimit: 0,
      pm10StandardLimit: 0,
      pm25BeforeHourPerc: 0,
      pm10BeforeHourPerc: 0,
      activeColor: "#699fff",
      progress: {},
      type: 1, // pm2.5 => 1, pm10 => 2
      //Data1 实时监测
      chart1: {
        title: "Data1 实时监测",
        date: moment(),
        time: moment(),
        now: null,
        timer: null,
      },
      //Data2 实时监测
      chart2: {
        title: "Data2 前一小时平均值",
        subtitle: "预警 次",
        date: moment(),
        time: moment(),
        now: null,
        timer: null,
      },
      chart3: {
        title: "Data3 前一天（24小时）监测平均值",
        subtitle: "预警 次",
        time: moment().subtract(1, "days"),
        now: null,
        timer: null,
      },
      dateTime: moment().format("YYYY-MM-DD HH:mm:ss"),
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      //面板实测值
      this.Request(getEnvironmentalData(projectId)).then((res) => {
        if (res.status == "200") {
          this.environmentalData = res.body;
          this.environmentalData.measuredUpdatePeriod = moment(
            this.environmentalData.measuredUpdatePeriod
          ).format("HH:mm");
          this.changeProccess();
        } else {
          this.$message({
            type: "error",
            message: res.Message,
            center: "true",
          });
        }
      });
      //杨丞规则
      this.Request(getDustSet(projectId)).then((res) => {
        if (res.status == "200") {
          var data = res.body;
          this.pm25StandardLimit = data.pm25StandardLimit;
          this.pm10StandardLimit = data.pm10StandardLimit;
          this.pm25BeforeHourPerc = data.beforeHourPerc;
          this.pm10BeforeHourPerc = data.pm10BeforeHourPerc;
          this.$nextTick(() => {
            this.changeProccess();
          });
        } else {
          this.$message({
            type: "error",
            message: res.Message,
            center: "true",
          });
        }
      });
      //杨丞实时监测

      var params = {
        projectId: projectId,
        type: this.type,
        dateTime: this.dateTime,
      };
      this.Request(selectDustChartByReal(params)).then((res) => {
        if (res.status == "200") {
          //console.log("data1实时监测", res);
          const mainChart = res.body.mainChart;

          this.handleLineData(mainChart);
        } else {
          this.$message({
            type: "error",
            message: res.Message,
            center: "true",
          });
        }
      });
      //前一小时平均值
      this.Request(selectDustChartByHour(params)).then((res) => {
        if (res.status == "200") {
          //console.log("data2实时监测", res);

          const { mainChart, slaveChart } = res.body;
          this.handleHourData(mainChart, slaveChart);
        } else {
          this.$message({
            type: "error",
            message: res.Message,
            center: "true",
          });
        }
      });
      // 前一天24小时监测平均值

      this.Request(selectDustChartByDay(params)).then((res) => {
        if (res.status == "200") {
          //console.log("data3实时监测", res);
          const { mainChart, slaveChart } = res.body;
          this.handleDayData(mainChart, slaveChart);
        } else {
          this.$message({
            type: "error",
            message: res.Message,
            center: "true",
          });
        }
      });
    },
    //进度调
    changeProccess() {
      /********excess ******/
      console.log(
        "this.environmentalData.pm25WbReleaseValue",
        this.environmentalData.pm25WbReleaseValue
      );
      console.log(
        "this.environmentalData.pm10WbReleaseValue",
        this.environmentalData.pm10WbReleaseValue
      );
      console.log("this.pm25BeforeHourPerc", this.pm25BeforeHourPerc);
      console.log("this.pm10BeforeHourPerc", this.pm10BeforeHourPerc);
      let defaultNormal = parseInt(
        (this.type === 1
          ? this.environmentalData.pm25WbReleaseValue
          : this.environmentalData.pm10WbReleaseValue) *
          (1 +
            (this.type === 1
              ? this.pm25BeforeHourPerc
              : this.pm10BeforeHourPerc) /
              100)
      );
      let defaultExcess = parseInt(
        this.type === 1 ? this.pm25StandardLimit : this.pm10StandardLimit
      );
      const value = parseInt(
        this.type === 1
          ? this.environmentalData.pm25MeasuredValue
          : this.environmentalData.pm10MeasuredValue
      );
      /****** normal********/
      const normal =
        defaultNormal > defaultExcess ? defaultExcess : defaultNormal;
      const excess =
        defaultNormal > defaultExcess ? defaultNormal : defaultExcess;
      // console.log("环境评测-value", value);
      // console.log("环境评测-excess", excess);
      // console.log("环境评测-normal", normal);
      this.progress = {
        normal,
        excess,
        value: value > excess ? 100 : value > normal ? 66.66 : 33.33,
      };
      console.log("progress", this.progress);
    },
    //data1 chart图
    handleLineData(data) {
      const xList = Array(60)
        .fill(0)
        .map((v, i) => i);
      var effectData = [];
      if (data.length != 0) {
        const total = 60;
        if (data.length === total) {
          effectData = data.map((item) => item.monVal);
        } else {
          // 将数据转换成 key/value
          const timesData = data.reduce((times, item) => {
            times[Number(moment(item.xtime).format("mm"))] = item.monVal;
            return times;
          }, {});
          // 计算最新数据时间与当前选择的时间
          const selectedHour = Number(moment(this.chart1.time).format("HH"));
          const newestHour = Number(
            moment(this.environmentalData.measuredUpdatePeriod).format("HH")
          );
          const selectedMinute = Number(moment(this.chart1.time).format("mm"));
          const newestMinute = Number(
            moment(this.environmentalData.measuredUpdatePeriod).format("mm")
          );
          let defaultValue = data[0].monVal;
          const count =
            newestHour === selectedHour
              ? (selectedMinute > newestMinute
                  ? newestMinute
                  : selectedMinute) + 1
              : total;
          effectData = Array(count)
            .fill()
            .map((v, i) => {
              const currentData = timesData[String(i)] || defaultValue;
              defaultValue = currentData;
              return currentData;
            });
        }
      } else {
        effectData = [0];
      }
      const self = this;
      const now = new Date().getHours();
      // const warnLine = now >= 6 && now < 22 ? 70 : 55;
      let warnLine;
      this.type == 1
        ? (warnLine = this.pm25StandardLimit)
        : (warnLine = this.pm10StandardLimit);
      this.chart1.now = moment();

      //判断有没有数据
      if (effectData.length == 0) {
        var max = 100;
      } else {
        // TODO:
        var max = effectData.reduce(function (a, b) {
          return b > a ? b : a;
        });
      }
      const interval = Math.max(Math.round(max / 5), 15);
      max =
        max > this.pm25StandardLimit
          ? (Math.ceil(max / interval) + 1) * interval
          : (Math.ceil(this.pm25StandardLimit / interval) + 1) * interval;
      var echarts = require("echarts");
      // 基于准备好的dom，初始化echarts实例
      var myChart = echarts.init(document.getElementById("data1"));

      this.chart1.options = {
        grid: {
          x: 35, //据左边距离
          y: 30, //据上边距离
          x2: 35, //据右边距离
          y2: 20, //据下边距离
        },

        color: "#699FFF",
        tooltip: {
          trigger: "none",
          axisPointer: {
            type: "cross",
          },
        },
        xAxis: {
          type: "category",
          name: "(分)",
          axisTick: {
            alignWithLabel: true,
          },
          nameTextStyle: {
            fontSize: 12,
            color: "#000",
          },
          axisLabel: {
            fontSize: 10,
            color: "#989A9C",
          },
          axisLine: {
            onZero: false,
            lineStyle: {
              color: "#CFD3E3",
            },
          },
          axisPointer: {
            label: {
              formatter(params) {
                return `${text[self.type - 1]} ${params.value}`;
              },
            },
          },
          data: xList,
        },
        yAxis: {
          type: "value",
          name: "ug/m³",
          max: max,
          interval,
          nameTextStyle: {
            fontSize: 12,
            color: "#000",
          },
          axisLabel: {
            fontSize: 10,
            color: "#989A9C",
          },
          axisLine: {
            onZero: false,
            lineStyle: {
              color: "#CFD3E3",
            },
          },
        },
        series: {
          name: `${text[self.type - 1]}（ug/m³）`,
          type: "line",
          smooth: true,
          data: effectData,
          markPoint: {
            data: [
              {
                name: "周最低",
                value: effectData[effectData.length - 1],
                coord: [
                  effectData.length - 1,
                  effectData[effectData.length - 1],
                ],
                symbolSize: 40,
                label: {
                  fontSize: 12,
                  fontWeight: "bold",
                },
              },
            ],
          },
          markLine: {
            animation: false,
            symbol: "none",
            data: [{ name: "警戒线", yAxis: warnLine }],
            lineStyle: {
              color: "#FFB200",
            },
          },
        },
      };
      myChart.setOption(this.chart1.options);
    },
    //data2 chart图
    handleHourData(mainChart, slaveChart) {
      const self = this;
      this.chart2.now = moment();
      let count = 0;
      let warnLine;
      this.type == 1
        ? (warnLine = this.pm25StandardLimit)
        : (warnLine = this.pm10StandardLimit);
      const effectMainChart = mainChart.map((item) => {
        let color = "#04BD70";
        if (item.isWarn) {
          count += 1;
          color = "#f5b501";
        }
        return {
          value: parseInt(item.monVal, 10),
          itemStyle: {
            color,
          },
          label: {
            show: Boolean(item.monVal),
          },
        };
      });
      this.chart2.subtitle = `预警${count}次`;

      let max = Math.max(
        ...[...slaveChart, ...effectMainChart.map((item) => item.value)]
      ); // 最大值
      const interval = Math.max(Math.round(max / 5), 15);
      if (max > warnLine) {
        max = (Math.ceil(max / interval) + 1) * interval;
      } else {
        max = (Math.ceil(warnLine / interval) + 1) * interval;
      }
      var echarts = require("echarts");
      // 基于准备好的dom，初始化echarts实例
      var myChart = echarts.init(document.getElementById("data2"));

      this.chart2.options = {
        grid: {
          x: 35, //据左边距离
          y: 30, //据上边距离
          x2: 35, //据右边距离
          y2: 40, //据下边距离
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
            crossStyle: {
              color: "#999",
            },
          },
        },
        legend: {
          data: ["气象站发布值", `前一小时平均值`],
          left: "center",
          bottom: 0,
          textStyle: {
            fontSize: 12,
          },
        },
        xAxis: {
          type: "category",
          name: "(时)",
          data: [
            0,
            1,
            2,
            3,
            4,
            5,
            6,
            7,
            8,
            9,
            10,
            11,
            12,
            13,
            14,
            15,
            16,
            17,
            18,
            19,
            20,
            21,
            22,
            23,
          ],
          axisPointer: {
            type: "shadow",
          },

          axisLabel: {
            fontSize: 10,
            color: "#989A9C",
            formatter: "{value}",
          },
        },
        yAxis: {
          type: "value",
          name: "ug/m³",
          max: max,
          nameTextStyle: {
            fontSize: 12,
            color: "#000",
          },

          axisLine: {
            onZero: false,
            lineStyle: {
              color: "#CFD3E3",
            },
          },
          interval,
          axisLabel: {
            fontSize: 10,
            color: "#989A9C",
          },
        },
        series: [
          {
            name: `前一小时平均值`,
            type: "bar",
            label: {
              normal: {
                show: false,
                  position: 'outside',
                  color: "transparent",
              
              },
            },
            itemStyle: {
              color: "#04BD70",
              fontSize: 12,
              
            },
            data: effectMainChart,
            markLine: {
              animation: false,
              symbol: "none",
              lineStyle: { color: "#FFB200" },
              data: [{ name: "警戒线", yAxis: warnLine }],
              // data: [
              //   [{ name: "警戒值", coord: [0, 55] }, { coord: [6, 55] }],
              //   [{ coord: [6, 70] }, { coord: [22, 70] }],
              //   [{ coord: [22, 55] }, { coord: [23, 55] }],
              //   [{ coord: [6, 55] }, { coord: [6, 70] }],
              //   [{ coord: [22, 55] }, { coord: [22, 70] }]
              // ]
            },
          },
          {
            name: "气象站发布值",
            type: "line",
            itemStyle: {
              color: "#699FFF",
            },
            data: slaveChart,
          },
        ],
      };
      myChart.setOption(this.chart2.options);
    },
    //data3 chart图
    handleDayData(mainChart, slaveChart) {
      const self = this;
      const maxDay = this.chart3.time.isBefore(
        moment().format("YYYY-MM-DD") + " 00:00:00"
      )
        ? parseInt(this.chart3.time.format("YYYY-MM-DD").slice(8, 10), 10)
        : parseInt(moment().format("YYYY-MM-DD").slice(8, 10), 10);
      const days = Array.apply(null, { length: 31 }).map((a, i) => i + 1);
      this.chart3.now = moment();
      let count = 0;
      let warnLine;
      this.type == 1
        ? (warnLine = this.pm25StandardLimit)
        : (warnLine = this.pm10StandardLimit);
      const chartData = mainChart.sort((a, b) =>
        a.xtime.localeCompare(b.xtime)
      );
      let monVal = 0;
      let isWarn = false;
      const renderArr = Array.apply(null, { length: maxDay }).map(
        (d, index) => {
          for (let i = 0; i < chartData.length; i++) {
            const per = chartData[i];
            if (parseInt(per.xtime.slice(8, 10), 10) - index === 1) {
              monVal = per.monVal;
              isWarn = per.isWarn;
              break;
            }
          }
          return {
            monVal,
            isWarn,
          };
        }
      );
      const effectMainChart = renderArr.map((item) => {
        let color = "#04BD70";
        if (item.isWarn) {
          count += 1;
          color = "#f5b501";
        }
        return {
          value: parseInt(item.monVal, 10),
          itemStyle: {
            color,
          },
          label: {
            show: Boolean(item.monVal),
          },
        };
      });
      this.chart3.subtitle = `预警${count}次`;
      // const max = Math.ceil(Math.max(...[...slaveChart, ...effectMainChart.map(item => item.value)]) / 50) * 50;
      let max = Math.max(
        ...[...slaveChart, ...effectMainChart.map((item) => item.value)]
      ); // 最大值
      const interval = Math.max(Math.round(max / 5), 15);
      if (max > warnLine) {
        max = (Math.ceil(max / interval) + 1) * interval;
      } else {
        max = (Math.ceil(warnLine / interval) + 1) * interval;
      }
      var echarts = require("echarts");
      // 基于准备好的dom，初始化echarts实例
      var myChart = echarts.init(document.getElementById("data3"));
      this.chart3.options = {
        grid: {
          x: 35, //据左边距离
          y: 30, //据上边距离
          x2: 35, //据右边距离
          y2: 40, //据下边距离
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
            crossStyle: {
              color: "#999",
            },
          },
        },
        legend: {
          left: "center",
          bottom: 0,
          data: ["气象站发布值", `前一天平均值`],
          textStyle: {
            fontSize: 12,
          },
        },
        xAxis: [
          {
            type: "category",
            name: "(日)",
            data: days,
            axisPointer: {
              type: "shadow",
            },
            nameTextStyle: {
              fontSize: 12,
              color: "#000",
            },
            axisLine: {
              onZero: false,
              lineStyle: {
                color: "#CFD3E3",
              },
            },
            axisLabel: {
              fontSize: 10,
              color: "#989A9C",
              formatter: "{value}",
            },
          },
        ],
        yAxis: {
          type: "value",
          name: "ug/m³",
          max: max,
          interval,
          nameTextStyle: {
            fontSize: 12,
            color: "#000",
          },
          axisLine: {
            onZero: false,
            lineStyle: {
              color: "#CFD3E3",
            },
          },
          axisLabel: {
            fontSize: 10,
            color: "#989A9C",
          },
        },
        series: [
          {
            name: `前一天平均值`,
            type: "bar",
            itemStyle: {
              color: "#04BD70",
            },
                label: {
              normal: {
                show: false,
                  position: 'outside',
                  color: "transparent",
              
              },
            },
            data: effectMainChart,
            markLine: {
              animation: false,
              symbol: "none",
              lineStyle: { color: "#FFB200" },
              data: [{ name: "警戒线", yAxis: warnLine }],
            },
          },
          {
            name: "气象站发布值",
            type: "line",
            itemStyle: {
              color: "#699FFF",
            },
            label: {
              show: false,
            },
            data: slaveChart,
          },
        ],
      };
      myChart.setOption(this.chart3.options);
    },
    onClickLeft() {
      this.$router.go(-1); //返回上一层
    },
    //标题切换
    titleTap(index, id) {
      this.titleIndex = index;
      this.type = id;
      this.$nextTick(() => {
        this.init();
        this.changeProccess();
      });
    },
    //去历史数据
    toHistory() {
      this.$router.push({ path: "/dustHistory" }); //返回上一层
    },
  },
};
</script>
<style lang="stylus" scoped>
@import '../../assets/common';

.btitle {
  color: #ffb200;
}

.hjpj_cont {
  padding-left: 30px;
  box-sizing: border-box;

  .left {
    width: 95px;
    height: 95px;
    border-radius: 100%;
    border: 6px solid #f00;
    font-size: 32px;
    font-family: Microsoft YaHei;
    font-weight: 400;
  }

  .right {
    height: 100%;
    text-align: center;
  }
}

.wetherCont {
  width: 100%;
  height: 300px;
  background: url('../../imgs/reportBg.jpg') no-repeat;
  background-size: 100% 100%;
  padding: 30px 0;
  box-sizing: border-box;
  font-size: 26px;

  .weather {
    width: 93%;
    margin: 0 auto;
    padding: 0 30px;
    box-sizing: border-box;
    background: rgba(249, 255, 252, 0.2);
    border-radius: 8px;
    height: 180px;

    .middleCont_left {
      color: #fff;
      text-align: center;

      .top1 {
        font-size: 28px;
        font-family: Microsoft YaHei;
        font-weight: 400;
        color: #FFFFFF;
        margin-bottom: 25px;
      }

      .top {
        font-weight: bold;
        font-size: 36px;
        font-family: Microsoft YaHei;
        font-weight: 400;
        color: #F2FE31;
        margin-bottom: 38px;
      }

      .bot {
        font-size: 28px;
      }
    }

    .middleCont_middle {
      width: 1px;
      height: 90px;
      background: #fff;
      opacity: 0.47;
    }
  }
}
</style>